package com.iie.bigVideo.service.impl;

import com.iie.bigVideo.entity.Video;
import com.iie.bigVideo.entity.dto.VideoDto;
import com.iie.bigVideo.mapper.VideoMapper;
import com.iie.bigVideo.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iie.bigVideo.utils.PageUtils;
import com.iie.bigVideo.utils.ResultUtils;
import com.iie.bigVideo.utils.UUIDUtils;
import com.iie.bigVideo.vo.ResultVO;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XXX
 * @since 2023-11-24
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {
    @Value("${server.port}")
    private String POST; //获取主机端口
    //相对路径
//    String property = System.getProperty("user.dir");
    @Value("${file.uploadFile}")
    private String uploadFile;
    @Value("${file.uploadFolder}")
    private String uploadFolder; // 静态资源实际存储路径
    @Value("${file.uploadFolderMysql}")
    private String uploadFolderMysql; //给数据库存的路径
    @Value("${file.uploadImage}")
    private String uploadImage; // 实际存储图片路径
    @Value("${file.uploadVideo}")
    private String uploadVideo; // 实际存储视频路径


    @Autowired
    private VideoMapper videoMapper;

    /**
     * 视频 全查询
     *
     * @return
     */
    @Override
    public ResultVO queryVideoList(HashMap<String, String> hashMap) {
        if (hashMap == null) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        Integer count = videoMapper.countVideo(hashMap);
        if (count == null || count == 0) {
            return ResultUtils.success(null); // 如果没有记录，则无需查询
        }
        int current = Integer.parseInt(hashMap.get("current"));
        int size = Integer.parseInt(hashMap.get("size"));
//        String sort = hashMap.get("sort");//排序标志
        // 计算当前页的起始索引
        int start = (current - 1) * size;
//        int sortInt = sort == null || sort.equals("0") ? 0 : Integer.parseInt(sort);//默认排序为0
        List<VideoDto> videoListPage = videoMapper.queryVideoList(start, size, hashMap);
        // 计算总页数
        int pageCount = (int) Math.ceil((double) count / size);
        if (videoListPage == null && videoListPage.size() <= 0) {
            return ResultUtils.error(201, "false", "无数据！");
        }
        // 创建并填充 PageUtils 对象
        PageUtils<VideoDto> videoPageUtils = new PageUtils<>();
        videoPageUtils.setCount(count);
        videoPageUtils.setPageCount(pageCount);
        videoPageUtils.setList(videoListPage);
        return ResultUtils.success(videoPageUtils);
    }

    /**
     * 修改视频信息
     *
     * @param video
     * @param videoFile
     * @param imgFile
     * @return
     */
    @Override
    public ResultVO updateVideo(Video video, MultipartFile videoFile, MultipartFile imgFile) {
        if (video == null) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        Video videoObj = videoMapper.queryVideoObjectByVideoId(String.valueOf(video.getVideoId()));//是否又此数据

        //视频名称 自动封装
        //视频路径
        if (videoFile != null) {
            //进行上传视频
            if (!videoFile.isEmpty()) {
                String uploadVideoFilePath = uploadFile(videoFile);
                if (StringUtils.isNotBlank(videoObj.getVideoUrl())) {
                    //物理删除原有的
                    deleteFile(uploadFile + videoObj.getVideoUrl());
                }
                video.setVideoUrl(uploadFolderMysql + uploadVideo + uploadVideoFilePath);
            }
        }
        //封面路径
        if (imgFile != null) {
            //进行上传图片
            if (!imgFile.isEmpty()) {
                String uploadImgFilePath = uploadFile(imgFile);
                if (StringUtils.isNotBlank(videoObj.getVideoMainImg())) {
                    //物理删除原有的
                    deleteFile(uploadFile + videoObj.getVideoMainImg());
                }
                video.setVideoMainImg(uploadFolderMysql + uploadImage + uploadImgFilePath);
            }
        }
        //更新时间
        video.setVideoUpdatedTime(new Date());
        Boolean updateVideo = videoMapper.updateVideo(video);
        if (!updateVideo) {
            return ResultUtils.error(201, "false", "修改失败！");
        }
        return ResultUtils.success("修改成功！");
    }

    /**
     * 删除视频 并 删除物理视频
     *
     * @param
     * @return
     */
    @Override
    public ResultVO deleteVideo(int videoId) {
        Video video = videoMapper.queryVideoObjectByVideoId(String.valueOf(videoId));//是否又此数据
        Integer integer = videoMapper.deleteVideo(video.getVideoId());//删除数据库视频信息
        if (integer <= 0) {
            return ResultUtils.error(201, "false", "视频删除失败！");
        }
        if (StringUtils.isNotBlank(video.getVideoMainImg()) && StringUtils.isNotBlank(video.getVideoUrl())) {
            //有内容
            //数据库视频信息删除成功了，开始删视频文件 和 图片了
            deleteFile(uploadFile + video.getVideoUrl());//删除视频
            deleteFile(uploadFile + video.getVideoMainImg());//删除图片
        } else if (StringUtils.isNotBlank(video.getVideoMainImg())) {
            //只有图片
            deleteFile(uploadFile + video.getVideoMainImg());//删除图片
        } else if (StringUtils.isNotBlank(video.getVideoUrl())) {
            //只有视频
            deleteFile(uploadFile + video.getVideoUrl());//删除视频s
        }
        return ResultUtils.success(integer);
    }

    /**
     * 删除文件
     *
     * @return
     */
    public static Boolean deleteFile(String filePath) {
        File dir = new File(filePath);
        //isFile()判断是否是文件，exists()判断该文件是否存在，delete()删除成功返回1失败则返回0
        if (dir.isFile() && dir.exists() && dir.delete()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据ID 查询 视频
     *
     * @param id
     * @return
     */
    @Override
    public ResultVO<VideoDto> queryByVideoId(int id) {
        if (id <= 0) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        VideoDto video = videoMapper.queryByVideoId(id);
        return ResultUtils.success(video);
    }

    /**
     * 添加视频信息
     *
     * @param video
     * @return
     */
    @Override
    public ResultVO addVideoObject(Video video, MultipartFile videoFile, MultipartFile imgFile) {
        if (video == null) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        //视频名称 自动封装
        //视频路径
        if (videoFile != null) {
            //进行上传视频
            if (!videoFile.isEmpty()) {
                String uploadVideoFilePath = uploadFile(videoFile);
                video.setVideoUrl(uploadFolderMysql + uploadVideo + uploadVideoFilePath);
            }
        }
        //封面路径
        if (imgFile != null) {
            //进行上传图片
            if (!imgFile.isEmpty()) {
                String uploadImgFilePath = uploadFile(imgFile);
                video.setVideoMainImg(uploadFolderMysql + uploadImage + uploadImgFilePath);
            }
        }
        //视频备注 自动封装
        //册ID 自动封装
        //创建时间
        video.setVideoCreatedTime(new Date());
        //更新时间
        video.setVideoUpdatedTime(new Date());
        //添加视频信息
        videoMapper.addVideoObject(video);
        //根据添加完操作，返回的ID 进行查询，是否添加成功？
        Video videoObject = videoMapper.queryByVideoId(video.getVideoId());
        if (videoObject == null) {
            return ResultUtils.error(201, "false", "添加失败！");
        }
        return ResultUtils.success(videoObject);
    }


    /**
     * 上传文件
     *
     * @return
     */
    public String uploadFile(MultipartFile file) {
        //校验上传的 是图片 还是 视频
        String contentType = file.getContentType();
        boolean image = contentType.startsWith("image");//如果是 image 开头 就是 图片
        String originalFilename = file.getOriginalFilename();//原文件名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));//扩展名
        String newFileName = "";
        try {
            if (image) {
                //图片
                //生成新的文件名
                newFileName = UUIDUtils.getUUID(16) + extension;
//                File fileObject = new File(Class.class.getClass().getResource("/").getPath() + uploadFolder + uploadImage);
                File fileObject = new File(uploadFolder + uploadImage);
                if (!fileObject.exists()) {
                    fileObject.mkdirs();//没有就创建
                }
                file.transferTo(new File(fileObject, newFileName));//对文件进行上传
            } else {
                //视频
                //生成新的文件名
                newFileName = UUIDUtils.getUUID(16) + extension;
//                File fileObject = new File(Class.class.getClass().getResource("/").getPath() + uploadFolder + uploadVideo);
                File fileObject = new File(uploadFolder + uploadVideo);
                if (!fileObject.exists()) {
                    fileObject.mkdirs();//没有就创建
                }
                file.transferTo(new File(fileObject, newFileName));//对文件进行上传
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return newFileName;
    }
}
